<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Setting } from '@element-plus/icons-vue'
import LayoutWithNav from '../components/LayoutWithNav.vue'

const router = useRouter()
const isLoggedIn = ref(false)
const userInfo = ref({
  username: '',
  phone: '',
  avatar_url: '',
  is_verified: false
})

// 计算头像URL
const getAvatarUrl = computed(() => {
  if (!userInfo.value.avatar_url) return ''
  const timestamp = new Date().getTime()
  const baseUrl = userInfo.value.avatar_url.startsWith('http') 
    ? userInfo.value.avatar_url 
    : `http://localhost:8000${userInfo.value.avatar_url}`
  return `${baseUrl}?t=${timestamp}`
})

// 检查登录状态
const checkLoginStatus = async () => {
  const token = localStorage.getItem('token')
  if (!token) {
    isLoggedIn.value = false
    return
  }

  try {
    const response = await axios.get('http://localhost:8000/users/userinfo/', {
      headers: {
        'Authorization': token.startsWith('Bearer ') ? token : `Bearer ${token}`
      }
    })

    if (response.data.code === 200) {
      isLoggedIn.value = true
      userInfo.value = {
        ...response.data.data,
        is_verified: response.data.data.is_verified || false
      }
    } else {
      isLoggedIn.value = false
      localStorage.removeItem('token')
      localStorage.removeItem('userid')
      localStorage.removeItem('refreshToken')
    }
  } catch (error) {
    console.error('Check login status error:', error)
    isLoggedIn.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('userid')
    localStorage.removeItem('refreshToken')
  }
}

// 处理头像点击上传
const handleAvatarClick = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }

  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = (e) => uploadAvatar(e)
  input.click()
}

// 上传头像
const uploadAvatar = async (event) => {
  if (!event.target.files || !event.target.files[0]) {
    ElMessage.error('请选择文件')
    return
  }

  const file = event.target.files[0]

  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件')
    return
  }

  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB')
    return
  }

  try {
    const formData = new FormData()
    formData.append('avatar', file)

    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('未登录状态')
      return
    }

    const response = await axios({
      method: 'post',
      url: 'http://localhost:8000/users/update_profile/',
      data: formData,
      headers: {
        'Authorization': token.startsWith('Bearer ') ? token : `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.code === 200) {
      // 更新头像URL并强制重新渲染
      const newAvatarUrl = response.data.data.avatar_url
      userInfo.value = {
        ...userInfo.value,
        avatar_url: newAvatarUrl
      }
      ElMessage.success('头像更新成功')
    } else {
      ElMessage.error(response.data.msg || '更新头像失败')
    }
  } catch (error) {
    console.error('Upload avatar error:', error)
    ElMessage.error('上传失败，请重试')
  }
}

// 退出登录
const logout = async () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('未登录状态')
      return
    }

    const cleanToken = token.replace(/^Bearer\s+/i, '').trim()

    const response = await axios.post('http://localhost:8000/users/logout/', null, {
      headers: {
        'Authorization': `Bearer ${cleanToken}`
      }
    })

    if (response.data.code === 200) {
      localStorage.removeItem('token')
      localStorage.removeItem('userid')
      localStorage.removeItem('refreshToken')
      ElMessage.success('退出成功')
      isLoggedIn.value = false
      router.push('/login')
    }
  } catch (error) {
    console.error('Logout error:', error)
    ElMessage.error('退出失败，请重试')
  }
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 跳转到设置页面
const goToSettings = () => {
  if (!isLoggedIn.value) {
    ElMessage.warning('请先登录')
    return
  }
  router.push('/settings')
}

onMounted(async () => {
  await checkLoginStatus() // 只在组件挂载时检查一次登录状态
})
</script>

<template>
  <LayoutWithNav>
    <div class="profile-container">
      <template v-if="isLoggedIn">
        <!-- 用户信息区域 -->
        <div class="user-info-section">
          <div class="avatar-wrapper" @click="handleAvatarClick">
            <el-avatar 
              :size="60" 
              :src="getAvatarUrl"
              icon="UserFilled"
            />
          </div>
          <div class="user-details">
            <h2>{{ userInfo.username || '用户1mBlkTtyvK' }}</h2>
            <p>手机号：{{ userInfo.phone ? userInfo.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '17*******91' }}</p>
          </div>
          <div class="verification-tag" :class="{ 'verified': userInfo.is_verified }">
            {{ userInfo.is_verified ? '已认证' : '未认证' }}
          </div>
          <el-button
            class="settings-btn"
            type="text"
            @click="goToSettings"
          >
            <el-icon :size="24"><Setting /></el-icon>
          </el-button>
        </div>

        <!-- 快捷功能区域 -->
        <div class="quick-actions-section">
          <div class="action-grid">
            <div class="action-item" @click="router.push('/favorites')">
              <div class="icon-wrapper">
                <i class="iconfont icon-home"></i>
              </div>
              <span>我的关注</span>
            </div>
            <div class="action-item">
              <div class="icon-wrapper">
                <i class="iconfont icon-card"></i>
              </div>
              <span>我的找房卡</span>
            </div>
            <div class="action-item">
              <div class="icon-wrapper">
                <i class="iconfont icon-contract"></i>
              </div>
              <span>合同协议</span>
            </div>
            <div class="action-item">
              <div class="icon-wrapper">
                <i class="iconfont icon-lock"></i>
              </div>
              <span>智能锁</span>
            </div>
            <div class="action-item">
              <div class="icon-wrapper">
                <i class="iconfont icon-delegate"></i>
              </div>
              <span>我的委托</span>
            </div>
          </div>
        </div>

        <!-- 其他功能区域 -->
        <div class="other-actions-section">
          <div class="action-grid">
            <div class="action-item">
              <div class="icon-wrapper">
                <i class="iconfont icon-history"></i>
              </div>
              <span>浏览记录</span>
            </div>
            <div class="action-item">
              <div class="icon-wrapper">
                <i class="iconfont icon-sign"></i>
              </div>
              <span>线上签约</span>
            </div>
            <div class="action-item">
              <div class="icon-wrapper">
                <i class="iconfont icon-about"></i>
              </div>
              <span>关于我们</span>
            </div>
          </div>
        </div>

        <!-- 我的房产区域 -->
        <div class="property-section">
          <div class="section-header">
            <h3>我的房产</h3>
            <i class="icon-arrow">›</i>
          </div>
        </div>

        <!-- 退出登录按钮 -->
        <div class="logout-section">
          <el-button type="danger" @click="logout" class="logout-btn">退出登录</el-button>
        </div>
      </template>

      <!-- 未登录状态显示登录提示 -->
      <template v-else>
        <div class="unlogin-profile">
          <!-- 头像和提示 -->
          <div class="unlogin-header">
            <el-avatar :size="60" icon="UserFilled" />
            <div class="login-register-btns">
              <el-button size="small" type="primary" @click="goToLogin">登录</el-button>
              <el-button size="small" @click="goToRegister">注册</el-button>
            </div>
          </div>

          <!-- 快捷功能区域 -->
          <div class="quick-actions-section">
            <div class="action-grid">
              <div class="action-item" @click="router.push('/favorites')">
                <div class="icon-wrapper">
                  <i class="iconfont icon-home"></i>
                </div>
                <span>我的关注</span>
              </div>
              <div class="action-item">
                <div class="icon-wrapper">
                  <i class="iconfont icon-card"></i>
                </div>
                <span>我的找房卡</span>
              </div>
              <div class="action-item">
                <div class="icon-wrapper">
                  <i class="iconfont icon-contract"></i>
                </div>
                <span>合同协议</span>
              </div>
              <div class="action-item">
                <div class="icon-wrapper">
                  <i class="iconfont icon-lock"></i>
                </div>
                <span>智能锁</span>
              </div>
              <div class="action-item">
                <div class="icon-wrapper">
                  <i class="iconfont icon-delegate"></i>
                </div>
                <span>我的委托</span>
              </div>
            </div>
          </div>

          <!-- 其他功能区域 -->
          <div class="other-actions-section">
            <div class="action-grid">
              <div class="action-item">
                <div class="icon-wrapper">
                  <i class="iconfont icon-history"></i>
                </div>
                <span>浏览记录</span>
              </div>
              <div class="action-item">
                <div class="icon-wrapper">
                  <i class="iconfont icon-sign"></i>
                </div>
                <span>线上签约</span>
              </div>
              <div class="action-item">
                <div class="icon-wrapper">
                  <i class="iconfont icon-about"></i>
                </div>
                <span>关于我们</span>
              </div>
            </div>
          </div>

          <!-- 我的房产区域 -->
          <div class="property-section">
            <div class="section-header">
              <h3>我的房产</h3>
              <i class="icon-arrow">›</i>
            </div>
          </div>
        </div>
      </template>
    </div>
  </LayoutWithNav>
</template>

<style scoped>
.profile-container {
  padding: 16px;
  background: #f5f5f5;
  min-height: calc(100vh - 56px);
}

.user-info-section {
  background: white;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.avatar-wrapper {
  margin-right: 16px;
  cursor: pointer;
}

.user-details {
  flex: 1;
}

.user-details h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.user-details p {
  margin: 4px 0 0;
  font-size: 14px;
  color: #666;
}

.quick-actions-section,
.other-actions-section {
  margin-top: 16px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-item:hover {
  background: #f0f0f0;
  transform: translateY(-2px);
}

.icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f0f9ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 4px;
}

.icon-wrapper i {
  font-size: 24px;
  color: #409EFF;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
  background: white;
  border-radius: 8px;
  padding: 8px;
  margin-bottom: 16px;
}

@media (max-width: 768px) {
  .action-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 480px) {
  .action-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

.property-section {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.icon-arrow {
  color: #999;
  font-size: 20px;
}

/* 图标样式 */
.iconfont {
  font-size: 24px;
}

.icon-home::before { content: '🏠'; }
.icon-card::before { content: '💳'; }
.icon-contract::before { content: '📄'; }
.icon-lock::before { content: '🔐'; }
.icon-delegate::before { content: '📋'; }
.icon-history::before { content: '⏱️'; }
.icon-sign::before { content: '✍️'; }
.icon-about::before { content: 'ℹ️'; }

.settings-btn {
  padding: 8px;
  color: #909399;
}

.settings-btn:hover {
  color: #8b2f8f;
}

.logout-section {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.logout-btn {
  width: 200px;
}

.verification-tag {
  background: #f5f5f5;
  color: #666;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  margin-right: 12px;
}

.verification-tag.verified {
  background: #e1f3d8;
  color: #67c23a;
}

.unlogin-profile {
  background: #fff;
}

.unlogin-header {
  padding: 20px;
  background: #fff;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
}

.login-register-btns {
  margin-left: 16px;
  display: flex;
  gap: 8px;
}

.login-register-btns .el-button {
  font-size: 14px;
  padding: 6px 12px;
}
</style>
